<?php


namespace app\erp\controller;


use app\erp\model\Cartdb;
use app\erp\model\Invoicedb;
use app\erp\model\OrderApplyEinvoicedb;
use app\erp\model\Orderdb;
use app\erp\model\UCartdb;
use app\erp\model\UInvoicedb;
use app\erp\model\UOrderdb;
use app\erp\model\Uploaddb;
use think\Cache;
use think\Db;
use think\Exception;

class Tuisong extends Base
{
    protected $cols = array(
        array(
            'field' => 'order_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
        ),
        array(
            'width' => 210,
            'toolbar' => '#tuisong_tool',
            'title' => '操作',
        ),
        array(
            'field' => 'order_type',
            'width' => 90,
            'title' => '订单类型',
            'templet' => '#order_typeTpl'
        ),
        array(
            'field' => 'is_change',
            'width' => 100,
            'templet' => '#is_changeTpl',
            'title' => '是否修改'
        ),
        array(
            'field' => 's_api_type',
            'width' => 80,
            'title' => '种类',
            'templet' => '#s_api_typeTpl'
        ),
        array(
            'field' => 's_invoice_api_bianhao',
            'width' => 80,
            'title' => '申请',
            'templet' => '#s_invoice_api_bianhaoTpl'
        ),
        array(
            'field' => 'out_order_no',
            'width' => 190,
            'title' => '军网订单号'
        ),
        array(
            'field' => 'order_money',
            'width' => 120,
            'title' => '订单金额',
            'templet' => '#order_moneyTpl'
        ),
        array(
            'field' => 's_invoice_title',
            'width' => 120,
            'title' => '发票抬头',
            'edit' => true
        ),
        array(
            'field' => 's_invoice_duty',
            'width' => 120,
            'title' => '发票税号',
            'edit' => true
        ),
        array(
            'field' => 's_invoice_beizhu',
            'width' => 120,
            'title' => '发票备注',
            'edit' => true
        ),
        array(
            'field' => 's_invoice_addr',
            'width' => 120,
            'title' => '地址',
            'edit' => true
        ),
        array(
            'field' => 's_invoice_tel',
            'width' => 120,
            'title' => '电话',
            'edit' => true
        ),
        array(
            'field' => 's_invoice_account',
            'width' => 120,
            'title' => '银行账号',
            'edit' => true
        ),
        array(
            'field' => 's_invoice_bank',
            'width' => 120,
            'title' => '开户行',
            'edit' => true
        ),
        
        array(
            'field' => 'gys_sh_state',
            'width' => 60,
            'title' => '收货',
            'templet' => '#gys_sh_stateTpl',
            'hide' => 'true'
        ),
        array(
            'field' => 'gys_fh_time',
            'width' => 150,
            'title' => '发货时间'
        ),
        array(
            'field' => 'apply_time',
            'width' => 160,
            'title' => '申请时间'
        ),
        array(
            'field' => 'ruku',
            'width' => 60,
            'title' => '入库',
            'templet' => '#rukuTpl'
        ),
        array(
            'field' => 'apply_state',
            'width' => 60,
            'title' => '审核',
            'templet' => '#apply_stateTpl2'
        ),
        
        array(
            'field' => 'returncode',
            'width' => 90,
            'title' => '电子发票',
            'templet' => '#returncode2Tpl'
        ),
        array(
            'field' => 'is_down',
            'width' => 60,
            'title' => '保存',
            'templet' => '#is_downTpl'
        ),
        array(
            'field' => 'invoice_state',
            'width' => 60,
            'title' => '推送',
            'templet' => '#invoice_stateTpl'
        ),
        array(
            'field' => 'm_supplier_name',
            'width' => 160,
            'title' => '供应商'
        ),
        array(
            'field' => 'm_useranme',
            'width' => 90,
            'title' => '审核人'
        ),
        array(
            'field' => 'apply_shehe_time',
            'width' => 160,
            'title' => '审核时间'
        ),

    );
    protected $goods_cols_invoice = array(
        array(
            'field' => 'goods_sku',
            'title' => '商品编号',
            'hide' => true
        ),
        array(
            'width' => 220,
            'field' => 'product_area',
            'title' => '税务大类',
            'edit' => true
        ),
        array(
            'width' => 180,
            'field' => 'shuiwu_id',
            'title' => '税务编码',
            'edit' => true
        ),
        array(
            'width' => 130,
            'field' => 'product_firm',
            'title' => '开票名称',
            'edit' => true
        ),
        array(
            'width' => 300,
            'field' => 'invoice_model',
            'title' => '规格型号(若不要型号，只需输一个空格)',
            'edit' => true
        ),
        array(
            'width' => 60,
            'field' => 'goods_unit',
            'title' => '单位',
            'edit' => true
        ),
        array(
            'width' => 90,
            'field' => 'sale_price',
            'title' => '单价'
        ),
        array(
            'width' => 60,
            'field' => 'goods_num',
            'title' => '数量'
        ),
        array(
            'width' => 90,
            'field' => 'goods_keywords',
            'title' => '税率',
            'edit' => true
        ),
        array(
            'width' => 120,
            'field' => 'all_sale_price',
            'title' => '总金额'
        ),
        array(
            'width' => 120,
            'field' => 'diy_beizhu',
            'title' => '订单备注',
            'edit' => true
        )
    );
    protected $goods_cols_invoice_old = array(
        array(
            'field' => 'goods_sku',
            'title' => '商品编号',
            'hide' => true
        ),
        array(
            'width' => 220,
            'field' => 'product_area',
            'title' => '税务大类'
        ),
        array(
            'width' => 180,
            'field' => 'shuiwu_id',
            'title' => '税务编码'
        ),
        array(
            'width' => 130,
            'field' => 'product_firm',
            'title' => '开票名称'
        ),
        array(
            'width' => 300,
            'field' => 'invoice_model',
            'title' => '规格型号(若不要型号，只需输一个空格)'
        ),
        array(
            'width' => 60,
            'field' => 'goods_unit',
            'title' => '单位'
        ),
        array(
            'width' => 90,
            'field' => 'sale_price',
            'title' => '单价'
        ),
        array(
            'width' => 60,
            'field' => 'goods_num',
            'title' => '数量'
        ),
        array(
            'width' => 90,
            'field' => 'goods_keywords',
            'title' => '税率'
        ),
        array(
            'width' => 120,
            'field' => 'all_sale_price',
            'title' => '总金额'
        ),
        array(
            'width' => 120,
            'field' => '',
            'title' => '',
        )
    );
    public $post = array();

    public function _initialize()
    {
        ini_set('memory_limit', '256M');
        parent::_initialize();
        $request = request();
        $param = $request->param();
        $this->post = $param;
    }

    // 导入excel
    public function excel($file)
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace($_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        // $objReader = \PHPExcel_IOFactory::createReader ( 'Excel2007' );
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $ColumnNum = \PHPExcel_Cell::columnIndexFromString($allColumn);
        $data = array();
        for ($rowIndex = 1; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $value = (string)$sheet->getCellByColumnAndRow(0, $rowIndex)->getValue();
                array_push($data, $value);
            }
        }
        $this->layuiReturn($data);
    }

    // 导入修改抬头
    public function excelTitle($file)
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace($_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        // $objReader = \PHPExcel_IOFactory::createReader ( 'Excel2007' );
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $ColumnNum = \PHPExcel_Cell::columnIndexFromString($allColumn);
        $data = array();
        for ($rowIndex = 1; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $value = (string)$sheet->getCellByColumnAndRow(0, $rowIndex)->getValue();
                array_push($data, $value);
                // 修改抬头
                $orderdb = new Orderdb();
                $get_order = $orderdb->where('out_order_no', $value)->find();
                if ($get_order) {
                    $invoicedb = new Invoicedb();
                    $get_invoice = $invoicedb->where('order_nos', $get_order['order_no'])->find();
                    if ($get_invoice) {
                        $save_data['invoice_title'] = (string)$sheet->getCellByColumnAndRow(1, $rowIndex)->getValue();
                        $get_invoice->save($save_data);
                    }
                }
            }
        }
        $this->layuiReturn($data);
    }

    public function index()
    {
        $this->assign('cols', json_encode($this->cols));
        $this->assign('goods_cols_invoice', json_encode($this->goods_cols_invoice));
        $this->assign('goods_cols_invoice_old', json_encode($this->goods_cols_invoice_old));
        return $this->fetch();
    }

    public function ajaxList()
    {
        $limit = $this->post['limit'] ?? 20;
        $orderdb = new Orderdb();
        if (!isset($this->post['apply_state'])) {
            $this->post['apply_state'] = -1;
        }

        if (isset($this->post['excel']) && $this->post['excel'] == 'true') {
            $orderdb->param['out_order_no_arr'] = $this->post['out_order_no_arr'];
        } else {
            $orderdb->param = $this->post;
            if (isset($orderdb->param['out_order_no_arr'])) {
                unset($orderdb->param['out_order_no_arr']);
            }
        }
        $get_order = $orderdb->with(['invoice', 'supplier', 'applyAuditAdmin'])->order('apply_time', 'desc')->paginate($limit);
        /*$get_order = $orderdb->fetchSql(true)->order('apply_time', 'desc')->select();
        halt($get_order);*/
        $result = $get_order->toArray();
        $this->layuiReturn($result['data'], $result['total']);
    }

    public function getCartList()
    {
        $cartdb = new Cartdb();
        $get_cart = $cartdb->with(['goods'])->where('order_no', $this->post['order_no'])->select();
        foreach ($get_cart as $key => $val) {
            if (isset($this->post['old']) && $this->post['old'] == 'yes') {
                $get_cart[$key]['goods_name'] = $val['goods']['goods_name'] ?? '';
                $get_cart[$key]['all_sale_price'] = number_format($val['goods_sale_price'] * $val['goods_num'], 2, '.', '');
                $get_cart[$key]['goods_jun_id'] = $val['goods']['jun_id'] ?? '';
                $get_cart[$key]['product_area'] = $val['goods']['product_area'];
                $get_cart[$key]['shuiwu_id'] = $val['goods']['shuiwu_id'];
                $get_cart[$key]['goods_unit'] = $val['goods']['goods_unit'];
                $get_cart[$key]['invoice_model'] = $val['goods']['invoice_model'];
                $get_cart[$key]['sale_price'] = $val['goods_sale_price'];
                $get_cart[$key]['product_firm'] = $val['goods']['product_firm'];
                $get_cart[$key]['goods_keywords'] = $val['goods']['goods_keywords'];
            } else {
                $get_cart[$key]['goods_name'] = $val['goods']['goods_name'] ?? '';
                $get_cart[$key]['all_sale_price'] = number_format($val['goods_sale_price'] * $val['goods_num'], 2, '.', '');
                $get_cart[$key]['goods_jun_id'] = $val['goods']['jun_id'] ?? '';
                $get_cart[$key]['product_area'] = $val['product_area'] ?: $val['goods']['product_area'];
                $get_cart[$key]['shuiwu_id'] = $val['shuiwu_id'] ?: $val['goods']['shuiwu_id'];
                $get_cart[$key]['goods_unit'] = $val['goods_unit'] ?: $val['goods']['goods_unit'];
                $get_cart[$key]['invoice_model'] = $val['invoice_model'] ?: $val['goods']['invoice_model'];
                $get_cart[$key]['sale_price'] = $val['goods_sale_price'] ?: $val['goods_sale_price'];
                $get_cart[$key]['product_firm'] = $val['product_firm'] ?: $val['goods']['product_firm'];
                $get_cart[$key]['goods_keywords'] = $val['goods_keywords'] ?: $val['goods']['goods_keywords'];
            }
        }
        $this->layuiReturn($get_cart, count($get_cart));
    }

    public function saveCartInfo()
    {
        $cartdb = new Cartdb();
        $get_cart = $cartdb->find($this->post['cart_id']);
        $save_data[$this->post['field']] = $this->post['value'];
        $get_cart->save($save_data);
        $this->layuiReturn('success');
    }

    // 单个审核发票
    public function oneApplyInfo()
    {
        $get_data = $this->post;
        $this->saveApplyInfo($get_data['order_no'], $get_data['apply_state'], $get_data['nopass_info']);
        $this->layuiReturn('success');
    }

    // 修改发票信息
    public function saveInvoiceField()
    {
        $get_data = $this->post;
        $invoicedb = new Invoicedb();
        $get_invoice = $invoicedb->where('order_nos', $get_data['order_no'])->find();
        if ($get_invoice) {
            $save_data[str_replace('s_', '', $get_data['field'])] = $get_data['value'];
            $get_invoice->save($save_data);
        }
        $this->layuiReturn('success');
    }

    /**
     * 审核申请发票
     */
    protected function saveApplyInfo($order_no, $apply_state, $nopass_info = '')
    {
        $cartdb = new Cartdb();
        $get_cart = $cartdb->where('order_no', $order_no)->select();
        if ($get_cart->toArray()) {
            foreach ($get_cart as $key => $val) {
                $cartdb->where('cart_id', $val['cart_id'])->update(['apply_state' => $apply_state, 'nopass_info' => $nopass_info]);
            }
        }


        $save_apply['order_no'] = $order_no;
        $save_apply['admin_id'] = MEMBER_ID;
        $save_apply['log'] = $apply_state == 3 ? '审核通过' : '驳回审核:' . $nopass_info;

        $orderApplyEinvoicedb = new OrderApplyEinvoicedb();
        $orderApplyEinvoicedb->save($save_apply);
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            $get_order->save(['apply_state' => $apply_state, 'apply_shehe_time' => time(), 'apply_audit_admin_id' => MEMBER_ID, 'nopass_info' => $nopass_info]);
            // 推送接口
            $msg_param = [];
            $msg_param['order_no'] = $get_order['out_order_no'];
            $msg_param['apply_state'] = $apply_state;
            $msg_param['remark'] = $nopass_info;
            pushTljMsg('einvoice_apply_state',$msg_param,$get_order['supplier_id']);
            // 推送完成
        }
        $UOrderdb = new UOrderdb();
        $UOrderdb->param['order_no'] = $order_no;
        $UOrderdb->param['apply_state'] = $apply_state;
        $UOrderdb->param['nopass_info'] = $nopass_info;
        $UOrderdb->param['apply_audit_admin_id'] = MEMBER_ID;
        //$UOrderdb->applyEinvoiceState();
        $UOrderdb->applyEinvoiceStateOnly();
        $cartdb = new Cartdb();
        $cartdb->where('order_no', $order_no)->update(['apply_state' => $apply_state]);
        $ucartdb = new UCartdb();
        $ucartdb->where('order_no', $order_no)->update(['apply_state' => $apply_state]);
    }

    // 下载电子发票到本地
    public function savelocation()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $invoicedb = new Invoicedb();
        $get_invoice = $invoicedb->where('order_nos', $this->post['order_no'])->find();
        $get_invoice->append(['invoice_proofs']);
        if (!$get_invoice) {
            $this->layuiReturn('未找到发票信息');
        }
        if (!$get_invoice['invoice_proof']) {
            $this->layuiReturn('还未申请发票');
        }
        $url = $get_invoice['invoice_proofs'];

        $this->post['invoice_id'] = $get_invoice['invoice_id'];
        $save_url = './uploads/invoice/' . $this->post['order_no'] . '_' . $this->post['invoice_id'] . '.pdf';
        if (strstr($url, 'dixintong')) {
            $this->layuiReturn('下载成功');
        }
        try {
            file_put_contents($save_url, file_get_contents($url));
        } catch (Exception $e) {
            $this->layuiReturn('下载错误');
        }
        $param ['size'] = 0;
        $param ['type'] = 'pdf';
        $param ['save_path'] = str_replace('uploads/', '', $save_url);
        $param ['file_name'] = $this->post['order_no'] . '_' . $this->post['invoice_id'] . '.pdf';
        $uploaddb = new Uploaddb();
        $uploaddb->param = $param;
        $info = $uploaddb->ajaxSave();
        $invoicedb = new Invoicedb();
        $get_invoice = $invoicedb->find($this->post['invoice_id']);
        $get_invoice->save(['invoice_proof' => $info['upload_id']]);
        $UInvoicedb = new UInvoicedb();
        $get_u_invoice = $UInvoicedb->where('order_nos', $get_invoice['order_nos'])->find();
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $get_invoice['order_nos'])->find();
        $get_order->save(['is_down' => 1]);
        if ($get_u_invoice) {
            $save_data = [];
            $save_data['invoice_proof'] = $info['upload_id'];
            $save_data['state'] = $get_invoice['state'];
            $save_data['api_return_no'] = $get_invoice['api_return_no'];
            $save_data['fapiaohao'] = $get_invoice['fapiaohao'];
            $save_data['fapiaodaima'] = $get_invoice['fapiaodaima'];
            $get_u_invoice->save($save_data);
            // 同步订单状态
            $UOrderdb = new UOrderdb();
            $get_u_order = $UOrderdb->where('order_no', $get_invoice['order_nos'])->find();
            if ($get_u_order && $get_order) {
                $save_data = [];
                $save_data['invoice_state'] = $get_order['invoice_state'];
                $save_data['returncode'] = $get_order['returncode'];
                $get_u_order->save([
                    'invoice_state' => $get_order['invoice_state'],
                    'returncode' => $get_order['returncode'],
                    'is_down' => 1
                ]);
            }
        }
        Cache::clear('order');
        Cache::clear('invoice');
        $this->layuiReturn('下载成功');
    }
}
